package org.example.fileServer;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.example.util.MyByteArrayDecoder;

/**
 * @classname: ServerInitializer
 * @description: TODO
 * @author: kaiser
 * @date: 2024/3/16 17:38
 * @version: 1.0
 */
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    private static final MyByteArrayDecoder DECODER = new MyByteArrayDecoder();
    private static final ByteArrayEncoder ENCODER = new ByteArrayEncoder();
    private static final ServerHandler SERVER_HANDLER = new ServerHandler();


    @Override
    public void initChannel(SocketChannel ch) throws Exception {
         ChannelPipeline pipeline = ch.pipeline();

         // 添加帧限定符来防止粘包现象
         pipeline.addLast(new DelimiterBasedFrameDecoder(102400000, Unpooled.copiedBuffer("END".getBytes())));
         // 解码和编码，应和客户端一致
         pipeline.addLast(DECODER);
         pipeline.addLast(ENCODER);

         // 业务逻辑实现类
         pipeline.addLast(SERVER_HANDLER);
    }
}
